package com.opencms.controller.base;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.opencms.freemarker.AdvertList;
import com.opencms.freemarker.ChannelList;
import com.opencms.freemarker.ContentList;
import com.opencms.freemarker.ContentView;
import com.opencms.freemarker.FriendLinkList;
import com.opencms.freemarker.NextContentTitle;
import com.opencms.freemarker.PreContentTitle;

import freemarker.template.Configuration;
import freemarker.template.TemplateModelException;


public abstract class FreemakerController {
	
	protected Configuration freemarkerCfg;
	protected Map<String, Object> data=new HashMap<String, Object>();
	@Autowired
	protected ServletContext context;
	@Autowired
	protected ChannelList channelList;
	@Autowired
	protected AdvertList advertList;
	@Autowired
	protected FriendLinkList friendLinkList ;
	@Autowired
	protected ContentList contentList;
	@Autowired
	protected ContentView contentView;
	@Autowired
	protected NextContentTitle nextContentTitle;
	@Autowired
	protected PreContentTitle preContentTitle;
  	/**
  	 * 初始化freemarker配置
  	 * @return
  	 * @throws TemplateModelException 
  	 */
	@ModelAttribute
  	public void  initCfg() throws TemplateModelException{
		data.put("path", context.getContextPath());
  		//判断context中是否有freemarkerCfg属性
  		if (context.getAttribute("freemarkerCfg")!=null) {
  			freemarkerCfg=(Configuration)context.getAttribute("freemarkerCfg");
  		}else {
  			freemarkerCfg = new Configuration();        
  			//加载模版        
  			freemarkerCfg.setServletContextForTemplateLoading(context, "/template");        
  			freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");    
  			//栏目宏
  			freemarkerCfg.setSharedVariable("channelList", channelList);
  			//广告宏
  			freemarkerCfg.setSharedVariable("advertList", advertList);
  			//友链宏
  			freemarkerCfg.setSharedVariable("friendLinkList", friendLinkList);
  			freemarkerCfg.setSharedVariable("contentList", contentList);
  			freemarkerCfg.setSharedVariable("contentView", contentView);
  			freemarkerCfg.setSharedVariable("nextContentTitle", nextContentTitle);
  			freemarkerCfg.setSharedVariable("preContentTitle", preContentTitle);
  		}
  	}

}
